package com.xiaomei.manager.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaomei.manager.dao.SysRoleMapper;
import com.xiaomei.manager.model.SysRole;
import com.xiaomei.manager.service.IResourceService;
import com.xiaomei.manager.service.IRoleService;

@Service
public class RoleServiceImpl implements IRoleService{
	@Autowired
	private SysRoleMapper sysRMapper;
	@Autowired
	private IResourceService resourceService;
	
	public SysRole createRole(SysRole role){
		if(sysRMapper.insert(role) > 0){
			role.setId(sysRMapper.selectLastInsertID());	
    		return role;
    	}else{
    		return null;
    	}
	}
	
    public SysRole updateRole(SysRole role){
    	if(sysRMapper.updateByPrimaryKey(role) > 0){
    		return role;
    	}else{
    		return null;
    	}
    }
    
    public void deleteRole(Long roleId){  	
    	if(sysRMapper.deleteByPrimaryKey(roleId) > 0){
    		
    	}        
    }

    public SysRole findOne(Long roleId){
    	return sysRMapper.selectByPrimaryKey(roleId);
    }
    public List<SysRole> findAll(){
    	return sysRMapper.selectAll();
    }

    /**
     * 根据角色编号得到角色标识符列表
     * @param roleIds
     * @return
     */
    public Set<String> findRoles(Long... roleIds){
    	 Set<String> roles = new HashSet<String>();
         for(Long roleId : roleIds) {
             SysRole role = findOne(roleId);
             if(role != null) {
                 roles.add(role.getRole());
             }
         }
         return roles;
    }

    /**
     * 根据角色编号得到权限字符串列表
     * @param roleIds
     * @return
     */
    public Set<String> findPermissions(Long[] roleIds){
    	  Set<Long> resourceIds = new HashSet<Long>();
          for(Long roleId : roleIds) {
              SysRole role = findOne(roleId);
              if(role != null) {
                  resourceIds.addAll(role.getResourceIdLst());
              }
          }
          return resourceService.findPermissions(resourceIds);
    }
}
